<template>
  <t-select 
    :modelValue="modelValue"
    :options="options"
    :loading="loading" 
    @search="onSupplier"
    @update:modelValue="onChage"
    filterable
  >
    <template #prefixIcon>
      <t-icon name="user" style="margin-right: 8px" />
    </template>
  </t-select>
</template>
<script setup>
  import { ref } from 'vue'
  import { get } from '@/api/erp/supplier'
  import index from '../index'

  const plugin = index.plugin
  const props = defineProps(['modelValue'])
  const emit = defineEmits(['update:modelValue', 'change'])
  const options = ref([])

  const loading = ref(false)
  
  // 加载供货商
  const onSupplier = name => {
    loading.value = true
    get({ name }).then(res => {
      options.value = res.data.map(item => {
        return {
          value: item.id,
          label: item.name 
        }
      })
      
      if(props.modelValue && options.value.findIndex(item => props.modelValue == item.value) == -1) {
        get({ id: props.modelValue, all: true }).then(res => {
          const supplier = res.map(item => {
            return {
              value: item.id,
              label: item.name 
            }
          })
          options.value.push(...supplier)
        })
      }

      options.value.unshift({
        value: 0,
        label: plugin.t('components.select.zero')
      })
    }).finally(() => {
      loading.value = false
    })
  }

  const onChage =  id => {
    emit('update:modelValue', id)
    emit('change', id)
  }

  onSupplier()
</script>